package com.example.recordersurfaceviewtest;

import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback{
    private SurfaceView mSurfaceView;
    private Button mRecord;
    private Button mStop;
    private String mVideoFile;
    private MediaRecorder mMediaRecorder;
    private boolean isRecording;
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        mSurfaceView = (SurfaceView) findViewById(R.id.sv_camera);
        mStop = (Button) findViewById(R.id.btn_stop);
        mRecord = (Button) findViewById(R.id.btn_record);
        mStop.setEnabled(false);
        mSurfaceHolder = mSurfaceView.getHolder();
        //eeeeee 将接口关联控件
        mSurfaceHolder.addCallback(this);
        mStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stop();
            }
        });
        mRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                record();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        mSurfaceHolder = holder;
        try {
            if (mCamera == null) {
                openCamera();
            }
            if (null != mCamera) {
                mCamera.setPreviewDisplay(mSurfaceHolder);//Camera屏幕通过SurfaceHolder与SurfaceView 进行绑定
                mCamera.startPreview();//开始预览
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "打开相机失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }

    private void openCamera() {
        mCamera = Camera.open(0);
        mCamera.setDisplayOrientation(getDegree());
    }

    private int getDegree() {
        //获取当前屏幕旋转的角度
        int rotating = this.getWindowManager().getDefaultDisplay().getRotation();
        int degree = 0;//度数
        //根据手机旋转的角度，来设置surfaceView的显示的角度
        switch (rotating) {
            case Surface.ROTATION_0:
                degree = 90;
                break;
            case Surface.ROTATION_90:
                degree = 0;
                break;
            case Surface.ROTATION_180:
                degree = 270;
                break;
            case Surface.ROTATION_270:
                degree = 180;
                break;
        }
        return degree;
    }

    private void record() {
        try {
            mVideoFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "Video" + System.currentTimeMillis() + ".mp4";
            createFile(mVideoFile);
            if (mMediaRecorder == null) {
                mMediaRecorder = new MediaRecorder();
                mCamera.unlock();
                mMediaRecorder.setCamera(mCamera);
            }
            mMediaRecorder.reset();
            // 设置从麦克风采集声音(或来自录像机的声音AudioSource.CAMCORDER)
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            // 设置从摄像头采集图像
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            // 设置视频文件的输出格式
            // 必须在设置声音编码格式、图像编码格式之前设置
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            // 设置声音编码的格式
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            // 设置图像编码的格式
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setVideoSize(1920, 1080);
            //每秒 4帧 视频的帧率和视频大小是需要硬件支持的，如果设置的帧率和视频大小,如果硬件不支持就会出现错误。
//            mMediaRecorder.setVideoFrameRate(20);
            mMediaRecorder.setOrientationHint(90);//视频旋转90度
            mMediaRecorder.setOutputFile(mVideoFile);
            Log.e("eeeeeeee", "RecordVideoActivity文件保存的路径为" + mVideoFile);
            // eeeeee 重点 指定使用SurfaceView来预览视频
            mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            System.out.println("---recording---");
            // 让record按钮不可用。
            mRecord.setEnabled(false);
            // 让stop按钮可用。
            mStop.setEnabled(true);
            isRecording = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param mVideoFile
     * 创建存储目录文件.
     */
    private void createFile(String mVideoFile) {
        File file = new File(mVideoFile);
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void stop() {
        if (isRecording) {
            release();
        }
    }

    private void release() {
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
            mRecord.setEnabled(true);
            mStop.setEnabled(true);
        }
    }
}